
$(document).ready(function(){
	com.main();
});

var com = {
	main : function(){
		setTimeout(function(){
			com.loadAli();
			com.loadBaidu();
		},1000)
		com.setReturnUrl();
	},
	url : {
		//获取上一页
		referrer : document.referrer
	},
	apiUrl : {
		//登 录
		loginUrl : homeUrl+"/web/user/login.d",
		//注册和登录
		registerAndLoginUrl : homeUrl+"/web/user/registerAndLogin.d",
		//手机注册和登录
		mobileRegisterAndLoginUrl : homeUrl+"/examine/mobile/to-code-page.d",
		//手机动态密码登录
		mobileLoginUrl : homeUrl+"/web/user/register-login-by-msg.d",
		//购物车列表
		cartListUrl : homeUrl+"/web/newshoppingcart/query-incart.d",
		//修改购物车数量
		editCartUrl : homeUrl+"/web/newshoppingcart/add-cartItem-proid-txt.d",
		//删除购物车
		delCartUrl : homeUrl+"/web/newshoppingcart/delete-cart-item.json",
		//购买
		buyUrl : homeUrl+"/web/newshoppingcart/add-cartItem-proid.d",
		//检测商品售卖状态
		checkProductStateUrl : homeUrl+"/web/newshoppingcart/check-product-sum-sale-time-book.json",
		//订单列表
		orderListUrl : homeUrl+"/web/neworder/order-list.json",
		//订单信息
		orderDetailsUrl : homeUrl+"/web/neworder/order-nopay-list.d",
		//检测是否预约
		checkBookUrl : homeUrl+"/book/check-book.json",
		//检测下一轮是否预约
		checkNextBookUrl : homeUrl+"/book/check-book-next.json",
		//保存预约
		saveBookUrl : homeUrl+"/book/save.d",
		//保存公测
		saveEventUrl : homeUrl+"/web/open-beta/save.d",
		//保存2公测
		saveNewEventUrl : homeUrl+"/web/open-beta-new/save.d",
		//检查公测是否报名成功
		checkEventUrl : homeUrl+"/web/open-beta-new/check-qulification.d",
		//获取手机列表
		getPhoneListUrl : homeUrl+"/web/user/get-phone-model.json",
		//退出登录
		removeSession : homeUrl+"/web/user/logout.d",
		//找回密码
		retrievePassUrl : homeUrl+"/web/user/exist.d",
		//修改密码
		editPassUrl : homeUrl+"/web/user/update-password.d",
		//获取验证码
		sendCodeUrl : apiUrl+"/api/web/verify/send.d",
		//检测验证码
		checkCodeUrl : apiUrl+"/api/web/verify/check.d",
		//发送手机动态密码
		checkMobileCodeUrl : apiUrl+"/api/web/verify/sendbynum.d",
		//使用优先购买码
		uxcodeUrl : homeUrl+"/uxm/get-uxm-info.json",
		//检测优先购买码是否有效
		checkUxcodeUrl : homeUrl+"/uxm/check.json",
		//省市区列表
		provinceCityUrl : homeUrl+"/address-district/get-address.json",
		//保存地址 移动
		saveAddressUrl : homeUrl+"/address/save-address.d",
		//保存地址旧的 PC
		saveOldAddressUrl : homeUrl+"/address/save-or-update.d",
		//保存订单
		saveOrderUrl : homeUrl+"/web/neworder/normal-add-order.d",
		//获取默认地址
		defultAddressUrl : homeUrl+"/address/get-defult-address.d",
		//设置默认地址
		setAddressUrl : homeUrl+"/address/set-default.d",
		//地址列表
		addressListUrl : homeUrl+"/address/get-dddress-list.json",
		//获取快递费用
		expPriceUrl : homeUrl+"/web/newshoppingcart/get-exp-price.json",
		//快递信息
		expInfoUrl : homeUrl+"/web/exp/query.json",
		//获取优惠码
		couponsUrl : homeUrl+"/draw/get-Coupons.json",
		//获取APP版本信息
		appVerUrl : homeUrl+"/versions/get-versions.json",
		//微信支付
		wxPayUrl : homeUrl+"/weixin-pay/pay.d",
		//查询微信支付状态
		wxPayStatusUrl : homeUrl+"/weixin-pay/get-pay-status.json",
		//获取优惠券
		getCouponsUrl : homeUrl+"/activitys-coupons/list.json",
		//检测优惠券
		checkCouponsUrl : homeUrl+"/activitys-coupons/get.json",
		//获取活动优惠券
		getCoupons : homeUrl+"/activitys-coupons/save.d",
		//获取公测名单
		getEventUrl : homeUrl+"/web/winner/get.json",
		//获取系统时间
		getSystemTimeUrl : homeUrl+"/activity-draw/get-time.json",
		//微信SDK验证
		getWxSignatureUrl : homeUrl+"/wx-get-signature.json",
		//微信SDK验证
		getWxSignatureUrl_v2 : protocol+"//restapi.iyunmai.com/openapi/wx/getApiTicket.json",
		//获取新闻资讯列表
		getNewsListUrl : homeUrl+"/news/news-list.json"
	},
	data : {
		user : null,
		haoqingActivitysId : 130,
		bookState : 0,
		hqBuyNum : 500,
		ip : "127.0.0.1",
		appShare : {  //app分享内容
			id : "",
			title : "",
			content : "",
			url : "",
			img : "",
			swich : 0  //0不显示 1显示
		}
	},
	/*
	 * ajax封装
	 */
	ajax : function(type,url,param,dataType,jsonp,callback,error){
		if(!url) return;
		var begin = Date.now(),time="";
		
		$.ajax({
			type : type || 'post',
			url : url,
			traditional : true,
			data : param || '',
			dataType : dataType || 'json',
			jsonp : jsonp,
			success : callback,
			error : error
		}).done(function(result){
			time=Date.now()-begin;
			window.__bl && __bl.api(url,true,time,result.code,result.msg);
		}).fail(function (error){
			time=Date.now()-begin;
			window.__bl && __bl.api(url,false,time,'ERROR',error.message);
		});
	},
	/*
	 * 官网跳转JD或TMALL购买好轻
	 */
	// buyHaoqing : function(product,text){
	// 	var $buyBtn=$("a[id*='buyBtn']"),url="",isM=window.location.pathname.indexOf("/m/")>-1?true:false,from=base.queryString("from"),target=from=="buy_tmall"?"tmall":from=="buy_jd"?"jd":"tmyz",len=$buyBtn.length,$this;
		
	// 	switch(product){
	// 		case "light":setUrl("light","light");break;
	// 		case "color":setUrl("color","light-color");break;
	// 		case "color2":setUrl("color2","light-color2");break;
	// 		case "mini":setUrl("mini","light-mini");break;
	// 		case "light2":setUrl("light2","light2");break;
	// 		case "se":setUrl("se","light-se");break;
	// 		case "mini2":setUrl("mini2","light-mini2");break;
	// 		case "yogamat":setUrl("yogamat","yogamat");break;
	// 		case "yogaball":setUrl("yogaball","yogaball");break;
	// 		case "battery7":setUrl("battery7","battery");break;
	// 		case "battery5":setUrl("battery5","battery5");break;
	// 		case "sportsTowel":setUrl("sportsTowel","sportsTowel");break;
	// 		case "wristBall":setUrl("wristBall","wristBall");break;
	// 		case "skip":setUrl("skip","skip");break;
	// 		case "elasticBands":setUrl("elasticBands","elasticBands");break;
	// 		case "floatingPlate":setUrl("floatingPlate","floatingPlate",isM?"":"jd");break;
	// 		case "yogablock":setUrl("yogablock","yogablock");break;
	// 		case "yogamat-cork":setUrl("yogamat-cork","yogamat-cork","yz");break;
	// 		case "goggles":setUrl("goggles","goggles","yz");break;
	// 		case "sportsJacket":setUrl("sportsJacket","sportsJacket","yz");break;
	// 		case "tightTrousers":setUrl("tightTrousers","tightTrousers","yz");break;
	// 		case "vibrationMassageDevice":setUrl("vibrationMassageDevice","vibrationMassageDevice");break;
	// 	}
		
	// 	for(var i=0;i<len;i++){
	// 		$this=$buyBtn.eq(i);
			
	// 		$this.attr({"href":url,"target":target?"_blank":""});
			
	// 		if(!$this.text()) $this.text(text||"立即购买");
	// 	}
		
	// 	function setUrl(name1,name2,single){
	// 		target=single=="home"?"":single?single:target;
	// 		url=homeUrl+(target=="tmall"?"/buy/?s=tm_"+name1:target=="jd"?"/buy/?s=jd_"+name1:target=="tb"?"/buy/?s=tb_"+name1:target=="yz"?"/buy/?s=yz_"+name1:target=="tmb"?"/buy/?s="+(isM?"tb":"tm")+"_"+name1:target=="tmyz"?"/buy/?s="+(isM?"yz":"tm")+"_"+name1:(isM?"/m":"")+"/shop/"+name2+"/");
	// 	}
	// },
	/*
	 * 微博分享
	 */
	// weiboShare : function(obj,arrs,num){
	// 	var $obj=$("#"+obj),keyLen=0,titleLen=0,keyRandom=0,titleRandom=0,keys="",titles="",url="";
		
	// 	keyLen=arrs.keyArrs.length;
		
	// 	for(var i=0;i<num;i++){
	// 		keyRandom=com.randoms(0,keyLen);
			
	// 		keys+=arrs.keyArrs[keyRandom]+(i==num-1?"、":"");
			
	// 		arrs.keyArrs.splice(keyRandom,1);
	// 		keyLen--;
	// 	}
		
	// 	titleLen=arrs.titleArrs.length;
	// 	titleRandom=com.randoms(0,titleLen);
	// 	titles=arrs.titleArrs[titleRandom];
	// 	titles=titles.replace("[key]",keys);
		
	// 	url="http://service.weibo.com/share/share.php?title="+encodeURIComponent(titles)+"&url="+arrs.url+"&appkey=6F1Zfb&pic="+arrs.imgUrl;
		
	// 	$obj.click(function(){
	// 		window.open(url,'云麦','height=100,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
	// 	});
	// },
	/*
	 * 用URL登录论坛
	 */
	// loginBbs : function (url){
	// 	com.ajax('GET',url,'','jsonp','callback',function(data){});
	// },
	/*
	 * 设置Cookie时间
	 * time分钟
	 */
	setCookieTime : function(time){
		var date = new Date();
		date.setTime(date.getTime()+(time*60*1000));
		return date;
	},
	/*
	 * 判断移动设备
	 */
	isMobile : function(){
		var u = navigator.userAgent;

		return {
			mobile : !!u.match(/AppleWebKit.*Mobile.*/),
			ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
			android : u.indexOf('Android') > -1,
			iPhone : u.indexOf('iPhone') > -1,
			iPad : u.indexOf('iPad') > -1,
			mac : u.indexOf('Mac OS X')>0
		};
	},
	/*
	 * 判断android版本号
	 */
	// androidVer : function(){
	// 	var u=window.navigator.userAgent,ver=u.substr(u.indexOf('Android') + 8,3);
		
	// 	return ver;
	// },
    /*
	 * 转换时间 
	 * dateType 输出类型
	 * timestamp 时间戳没有就默认系统时间
	 * type 没有为默认， 1 系统时间减时间戳得出差值时间描述， 2 系统时间减时间戳返回毫秒， 3 日期转时间戳
	 * 
	 * com.changeTime("YYYY年MM月DD日hh时mm分ss秒",1484656633000)
	 * com.changeTime("",1484656633000,1)
	 * com.changeTime("",1484656633000,2)
	 * com.changeTime("2017/06/08 00:00:00","",3)
	 */
	changeTime : function(dateType,timestamp,type){
		var sdts=new Date().getTime(),ts=timestamp?String(timestamp).length==10?timestamp*1000:timestamp*1:sdts,d=new Date(ts),year=d.getFullYear(),mon=d.getMonth()+1,day=d.getDate(),hou=d.getHours(),minu=d.getMinutes(),sec=d.getSeconds(),diff=0;
		
		mon=mon<10?"0"+mon:mon;
		day=day<10?"0"+day:day;
		hou=hou<10?"0"+hou:hou;
		minu=minu<10?"0"+minu:minu;
		sec=sec<10?"0"+sec:sec;
		
		if(type==1){
			diff=(sdts-ts)/1000|0;
			if(diff<=1*60) return "刚刚";
			else if(diff<=60*60&&diff>1*60) return (diff/60|0)+'分钟之前';
			else if(diff<=24*60*60&&diff>60*60) return (diff/(60*60)|0)+'小时之前';
			else return mon+'月'+day+'日';
		}else if(type==2){
			return sdts-ts;
		}else if(type==3){
			return dateType?new Date(dateType).getTime():new Date().getTime();
		}else{
			return dateType.replace("YYYY",year).replace("MM",mon).replace("DD",day).replace("hh",hou).replace("mm",minu).replace("ss",sec);	
		}
	},
	/*
	 * 设置动画样式
	 */
	animatStyle : function(style,type){
		return type==1?"animation:"+style+"; -webkit-animation:"+style+";":{"animation":style,"-webkit-animation":style};
	},
	/*
	 * 获取验证码
	//  */
	// changeVCode : function(obj){
	// 	obj.src="../code/get-image.d?v="+Math.random();
	// },
	/*
	 * 退出登录
	 */
	// removeSession : function(){
	// 	com.ajax('',com.apiUrl.removeSession,'','','',function(data){
	// 		$.cookie("user",null,{path:'/'});
	// 		window.location.href=$.cookie("loginReturnUrl");
	// 	});
	// },
	/*
	 * 是否登录
	 */
	// checkLogin : function(){
	// 	if(!base.isNull($.cookie("user"))) window.location.href=pub.url.loginUrl;
	// },
	/*
	 * 登录超时
	 */
	// isOverTime : function(textStatus){
	// 	if(textStatus=="error") window.location.href=pub.url.loginUrl;
	// },
	/*
	 * 关闭浏览器退出登录
	 */
	// ifAutoLogin : function(){
	// 	window.onbeforeunload=function(){
	// 		var n=window.event.screenX-window.screenLeft;
	// 		var b=n>document.documentElement.scrollWidth-20;
	// 		if(b&&window.event.clientY<0||window.event.altKey){
	// 			if($.cookie("autoLoginTime@yunmai")==0||!base.isNull($.cookie("autoLoginTime@yunmai"))) com.removeSession();
	// 		}
	// 	};
	// },
	/*
	 * 设置返回url
	 */
	setReturnUrl:function(url){
		if(window.location.href.indexOf("login.html")>0) return;
		$.cookie("loginReturnUrl",url||window.location.href,{path:'/',domain:'域名',expires:com.setCookieTime(60)});
	},
	/*
	 * 随机数
	 */
	randoms : function(mins,maxs){
		var mins=mins==0||mins?mins:1,maxs=maxs==0||maxs?maxs:10000;
		
		return (Math.random()*(maxs-mins)+mins)|0;
	},
	/*
	 * 百度统计
	 */
	loadBaidu : function(){
		$.ajax({
			type : "GET",
			url : protocol+"//hm.baidu.com/h.js?7f65ea8c38ac9004a5e3ce6515716b8a",
			dataType : "script",
			cache:true,
			success:function(){}
		});
	},
	/*
	 * 阿里云统计
	 */
	loadAli : function(){
		window.__bl=[];
		window.__bl.config={
			pid:"gor8ojsgyb@02717c29f9ce730",
			enableSPA:true,
			page:window.location.pathname||"index"
		};
		
		$.ajax({
			type : "GET",
			url : protocol+"//retcode.alicdn.com/retcode/bl.js",
			dataType : "script",
			cache:true,
			success:function(){}
		});
	},
	/*
	 * 加载客服系统
	 */
	loadKefu : function(){
		$.ajax({
			type : "GET",
			url : "http://kefu.easemob.com/webim/easemob.js?tenantId=18905&hide=false&sat=false",
			dataType : "script",
			cache:true,
			success:function(){}
		});
	},
	/*
	 * 获取IP
	 */
	getIp : function(){
		com.ajax('',protocol+'//bbs.iyunmai.com/ip.php','','jsonp','callback',function(data){
			if(data) com.data.ip=data;
		});
	},
	/*
	 * 文本框信息提示
	 */
	errorMsg : function(obj,msg){
		var $objBox=$("#"+obj+"Box"),$obj=$("#"+obj);

		if($("#errorMsg"+obj).length==0){
			$objBox.append('<div class="msg_box" id="errorMsg'+obj+'"></div>');
			
			$("#errorMsg"+obj).click(function(){
				$obj.focus();
				$objBox.removeClass("input_error");
				$(this).hide().css({"opacity":0.3,"transition-duration":"0s","transform":"translate3d(0,0,0)"});
			});
		}

		$("#errorMsg"+obj).text(msg).show().css({"transition-duration":"0.2s","transform":"translate3d(0,"+($objBox.height()-24)/2+"px,0)","opacity":1});
		$objBox.addClass("input_error");
	},
    /*
	 * 验证信息
	 */
    checkValue : function(type,value){
    	var regExp="";
    	
    	switch(type){
			case "user": //账号
				regExp=new RegExp("^[\u4e00-\u9fa5A-Za-z0-9-_]*$");
				break;
			case "tel": //手机号
				regExp=new RegExp("^1[2|3|4|5|7|8][0-9]\\d{8,8}$");
				break;
			case "pwd": //密码
				regExp=new RegExp("^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,12}$");
				break;
			case "code": //验证码
				regExp=new RegExp("^[a-zA-Z0-9]+$");
				break;
			case "num": //数字
				regExp=new RegExp("^[\0-9\.]*$");
				break;
			case "mail": //邮箱
				regExp=new RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$");
				break;
			case "zipCode": //邮政编码
				regExp=new RegExp(/^\d{6}$/);
				break;
			case "special": //特殊字符
				regExp=new RegExp(/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im);
				break;
			default:
		}
    	
    	return regExp.test(value);
    },
    /*
	 * 延时加载图片
	 */
	loadImg : function(){
		var imgLen=$("[name='load']").length,bgLen=$("[name='loadbg']").length,swich=true,setTimes="",$this="";
		
		$(window).ready(function(){
			if(swich) scrolls();
		});
		
		$(window).scroll(function(){
			if(swich) scrolls();
		});
		
		setTimes=setTimeout(function(){
			if(swich) loads();
		},2500);
		
		function scrolls(){
			if($(document).scrollTop()>100) loads();
		}
		
		function loads(){
			if(setTimes) clearTimeout(setTimes);
			
			for(var i=0;i<imgLen;i++){
				$this=$("[name='load']").eq(i);
				$this.attr("src",(pub.url.imgUrl?pub.url.imgUrl+$this.data("oss_src"):$this.data("src"))+"?t=201901301628");
			}
			
			for(var i=0;i<bgLen;i++){
				$this=$("[name='loadbg']").eq(i);
				if($this.data("bg")) $this.addClass($this.data("bg"));
			}
			
			swich=false;
		}
	},
    /*
	 * 分享
	 */
	appShare : function(){
		return '{"swich":"'+com.data.appShare.swich+'","id":"'+com.data.appShare.id+'","title":"'+encodeURIComponent(com.data.appShare.title)+'","content":"'+encodeURIComponent(com.data.appShare.content)+'","url":"'+encodeURIComponent(com.data.appShare.url)+'","img":"'+encodeURIComponent(com.data.appShare.img)+'"}';
	}
};